package com.GDOU.controller;
import com.GDOU.bean.Login;
import com.GDOU.bean.Manager;
import com.GDOU.bean.Student;
import com.GDOU.bean.Teacher;
import com.GDOU.service.LoginService;
import com.GDOU.service.TeacherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;

@RestController
public class UserController {

    @Autowired
    private LoginService loginService;

    @Autowired
    private TeacherService teacherService;


    //登录功能
    @PostMapping("/login.do")
    public Integer login(@RequestBody Login login, HttpServletRequest request){
        String username=login.getUsername();
        String password=login.getPassword();
        String role=login.getRole();

        //status: 0 账号或密码错误；1成功
        // 账号密码错误
        Object obj = null;
        if(role.equals("manager")){
            obj = loginService.managerLogin(username,password);
        } else if(role.equals("teacher")){
            obj = loginService.teacherLogin(username,password);
        } else if(role.equals("student")){
            obj = loginService.studentLogin(username,password);
        }

        if(obj == null) return 0;
        else {
            //保存用户登陆的信息到Session域中
            if(role.equals("student")){
                Student student=(Student) obj;
                Integer teaId = student.getTeaId();
                Teacher teacher = teacherService.getTeacherById(teaId);
                request.getSession().setAttribute("role",role);
                request.getSession().setAttribute("student",student);
                request.getSession().setAttribute("teacher",teacher);
            }else if (role.equals("manager")){
                Manager manager=(Manager) obj;
                request.getSession().setAttribute("role",role);
                request.getSession().setAttribute("manager",manager);
            }else {
                Teacher teacher=(Teacher) obj;
                request.getSession().setAttribute("role",role);
                request.getSession().setAttribute("teacher",teacher);
            }
            return 1;
        }
    }
}
